import React, { createContext, useContext, useState, useCallback, ReactNode, useEffect } from 'react';
import { ExecutionRecord, TaskHistoryContextType } from './types';
import recordService from '../services/recordService';

const TaskHistoryContext = createContext<TaskHistoryContextType | undefined>(undefined);


export const TaskHistoryProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [executionRecords, setExecutionRecords] = useState<ExecutionRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 通用错误处理函数
  const handleError = (err: unknown, message: string) => {
    setError(err instanceof Error ? err.message : message);
    setLoading(false);
  };

  // 获取执行记录
  const fetchExecutionRecords = useCallback(async (taskId?: string) => {
    try {
      setLoading(true);
      setError(null);
      const records = await recordService.getExecutionRecords({
        limit: 100,
        taskId
      });
      setExecutionRecords(Array.isArray(records) && records.length > 0 ? records : []);
    } catch (err) {
      handleError(err, '获取执行记录失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 添加执行记录
  const addExecutionRecord = useCallback(async (record: Omit<ExecutionRecord, 'id' | 'createdAt'>) => {
    try {
      setLoading(true);
      setError(null);
      const newRecord = await recordService.createExecutionRecord(record);
      if (!newRecord) {
        throw new Error('添加执行记录失败：返回数据为空');
      }
      setExecutionRecords(prev => [...prev, newRecord]);
    } catch (err) {
      handleError(err, '添加执行记录失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  // 更新执行记录
  const updateExecutionRecord = useCallback(async (id: string, record: Partial<ExecutionRecord>) => {
    try {
      setLoading(true);
      setError(null);
      const updatedRecord = await recordService.updateExecutionRecord(id, record);
      setExecutionRecords(prev => 
        prev.map(r => r.id === id ? updatedRecord : r)
      );
    } catch (err) {
      handleError(err, '更新执行记录失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  // 删除执行记录
  const deleteExecutionRecord = useCallback(async (id: string) => {
    try {
      setLoading(true);
      setError(null);
      await recordService.deleteExecutionRecord(id);
      setExecutionRecords(prev => prev.filter(r => r.id !== id));
    } catch (err) {
      handleError(err, '删除执行记录失败');
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  // 初始加载数据
  useEffect(() => {
    fetchExecutionRecords();
  }, [fetchExecutionRecords]);

  const value = {
    executionRecords,
    loading,
    error,
    fetchExecutionRecords,
    addExecutionRecord,
    updateExecutionRecord,
    deleteExecutionRecord,
  };

  return <TaskHistoryContext.Provider value={value}>{children}</TaskHistoryContext.Provider>;
};

export const useTaskHistoryContext = () => {
  const context = useContext(TaskHistoryContext);
  if (context === undefined) {
    throw new Error('useTaskHistoryContext must be used within a TaskHistoryProvider');
  }
  return context;
}; 